package com.jintoufs.web.action;

import com.google.code.kaptcha.Constants;
import com.jintoufs.domain.constants.MessageConstants;
import com.jintoufs.domain.customer.Customer;
import com.jintoufs.domain.hotel.HotelOrder;
import com.jintoufs.domain.scene.SceneOrder;
import com.jintoufs.domain.tour.TourRouteOrder;
import com.jintoufs.service.customer.CustomerService;
import com.jintoufs.service.hotel.HotelOrderService;
import com.jintoufs.service.scene.SceneOrderService;
import com.jintoufs.service.sys.DictionaryService;
import com.jintoufs.service.tour.TourRouteService;
import com.jintoufs.service.weixin.WxRefundService;
import com.jintoufs.util.convert.JSONUtils;
import com.jintoufs.util.http.HttpUtils;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.web.action.shiro.CaptchaUsernamePasswordToken;
import com.jintoufs.web.action.shiro.IncorrectCaptchaException;
import com.jintoufs.web.action.shiro.UnModifyDefaultPasswordException;
import com.jintoufs.web.action.shiro.bind.annotation.CurrentUser;
import com.jintoufs.web.action.support.SupportAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.Session;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.jintoufs.util.CardCodeGenerator;


/**
 * 包括登陆、注册、忘记密码等前台Action
 *
 * @author tcq
 */
@Controller
public class IndexAction extends SupportAction {

    @Autowired
    private CustomerService customerService;
    @Resource
    private DictionaryService dictionaryService;
    @Resource
    private WxRefundService refundService;
    @Resource
    private HotelOrderService hotelOrderService;
    @Resource
    private SceneOrderService sceneOrderService;
    @Resource
    private TourRouteService tourRouteService;


    @RequestMapping(value = "/login")
    public String showLoginForm(HttpServletRequest req, Model model) {
        String exceptionClassName = (String) req.getAttribute("shiroLoginFailure");
        String username = getString(req, "username");
        String error = null;
        boolean modified = true;
        if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
            error = "用户不存在";
        } else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
            error = "用户名/密码错误";
        } else if (AuthenticationException.class.getName().equals(exceptionClassName)) {
            error = "无权限访问该目录";
        } else if (IncorrectCaptchaException.class.getName().equals(exceptionClassName)) {
            error = "验证码错误";
        } else if (UnModifyDefaultPasswordException.class.getName().equals(exceptionClassName)) {
            modified = false;
        }else if (ExcessiveAttemptsException.class.getName().equals(exceptionClassName)) {
            error = "密码错误次数过多，请10分钟后再试";
        } else if (exceptionClassName != null) {
            error = "其他错误：" + exceptionClassName;
        }

        model.addAttribute("username", username);
        model.addAttribute("error", error);
        model.addAttribute("modified", modified);
        if (req.getParameter("forceLogout") != null) {
            model.addAttribute("error", "您已经被管理员强制退出，请重新登录");
        }
        return "/login";
    }

    @RequestMapping("sendKaptchaImage")
    @ResponseBody
    public AjaxMsg sendKaptchaImage(String telephone, HttpServletRequest request,String captcha){
        AjaxMsg ajaxMsg = new AjaxMsg();
        String captchacode = (String) request.getSession().getAttribute(MessageConstants.MESSAGE_KAPTCHA_SESSION_KEY);

//        String captcha = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        if (captcha != null && !captcha.equals(captchacode)) {
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("验证码错误");
        }else {
            Map<String,Object> params = new HashMap<>();
            params.put("userName",telephone);
            try {
                Integer type = customerService.queryByParams(params).get(0).getType();
                if (type==0){
                    Integer smsId;
                    ArrayList<String> smsParams = new ArrayList<String>();
                    smsId = Integer.valueOf(dictionaryService.getDicByKeyNo("FORGOT_PASSWORD_SMS").get(0).getCaption());
                    String code = CardCodeGenerator.generateRandomPassword();
                    smsParams.add(code);
                    refundService.sendOrderSms(telephone,smsId,smsParams);
                    request.getSession().setAttribute(telephone,code);
                }else {
                    ajaxMsg.setCode(AjaxMsg.FAILURE);
                    ajaxMsg.setMessage("没有找到该用户");
                }
            }catch (Exception e){
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("没有找到该用户");
            }

        }
        return ajaxMsg;
    }

    @RequestMapping("initPassword")
    @ResponseBody
    public AjaxMsg initPassword(String username,String password,HttpServletRequest request){
        AjaxMsg ajaxMsg = new AjaxMsg();
        if (request.getSession().getAttribute(username).equals(password)){
            Map<String,Object> params = new HashMap<>();
            params.put("userName",username);
            try {
                Customer customer = customerService.queryByParams(params).get(0);
                customerService.initPassword(customer.getId());
            }catch (Exception e){
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("没有找到该用户");
            }
        }
        return ajaxMsg;
    }

    @RequestMapping("dashboard")
    public String dashboard(Byte isLogin,Integer num, @CurrentUser Customer user,Model model) throws IOException {
        if (isLogin == null || isLogin != 0) {
            user.setLastLoginTime(new Date());
            customerService.update(user);
        }
        if (ValidUtil.isEmpty(num)){
            num=6;
        }else {
            num-=1;
        }
        model.addAttribute("hotel",hotelOrderService.getIndexData(num,user.getId()));
        model.addAttribute("scene",sceneOrderService.getIndexData(num,user.getId()));
        model.addAttribute("agency",tourRouteService.getIndexData(num,user.getId()));

        model.addAttribute("modified",user.getModified());
        return "/dashboard";
    }

    @RequestMapping("/getGeocoder")
    @ResponseBody
    public String geocoder(String lng,String lat)  {
        String url = "http://api.map.baidu.com/geocoder/v2/?location="+lat+","+lng+"&output=json&ak=lhWGKCZStt1t0uDT98cH0nBGjxNpu3L1";
        String resp = HttpUtils.getURLContent(url,"utf-8");
        JSONObject jsonObject = JSONUtils.toJSONObject(resp);
        JSONObject result = JSONUtils.toJSONObject(jsonObject.get("result"));
        return result.getString("sematic_description");
    }
}